# vintage计算


## 1.交易明细表导入，包含账号、消费日期(贷前取申请日期)、逾期期数、账单日期(本次使用账单日、最低应缴还款期限还原)
df_stmp_all=pd.read_csv(r"C:\Users\user2\建模\建模-明细数据\stmt\所有数据\S24_STMT_HIS_20170601_20200331_1.csv",dtype=str)
tmp=pd.read_csv(r"C:\Users\user2\建模\建模-明细数据\stmt\所有数据\S24_STMT_HIS_20200401_20201231_1.csv",dtype=str)
df_stmp_all=df_stmp_all.append(tmp)

df_stmp_all["消费日期月份"]=pd.to_datetime(df_stmp_all['消费日期']).apply(lambda x:datetime(x.year,x.month,1))

## 2.使用账单日、最低应缴还款期限还原账单日期，如已经有账单日期可跳过此步骤
def  aaaa(x,y):
    from datetime import datetime
    if x=="01":
        return datetime(y.year,y.month,1)
    elif x=="15":
        if y.month==1:
            return datetime(y.year-1,12,15)
        else:
            return datetime(y.year,y.month-1,15)

df_stmp_all["账单日期"]=df_stmp_all.apply(lambda x:aaaa(x["账单日"],x["最低应缴还款期限"]),axis=1) 

## 3.使用账单日期和消费日期构造账龄
def mob(x,y):
    
    """
    x:账单日期，y:消费日期
    """
    if x.day>y.day:
        return x.year*12+x.month-y.year*12-y.month
    else:
        return x.year*12+x.month-y.year*12-y.month-1
        
df_stmp_all["MOB"]=df_stmp_all[["账单日期","消费日期日期格式"]].apply(lambda x:mob(x["账单日期"],x["消费日期日期格式"]),axis=1)

## 4.根据逾期期数构造逾期状态
df_stmp_all["M1+"]=df_stmp_all["逾期期数"].apply(lambda x: 1 if x>=1 else 0)
df_stmp_all["M2+"]=df_stmp_all["逾期期数"].apply(lambda x: 1 if x>=2 else 0)
df_stmp_all["M3+"]=df_stmp_all["逾期期数"].apply(lambda x: 1 if x>=3 else 0)
df_stmp_all["M4+"]=df_stmp_all["逾期期数"].apply(lambda x: 1 if x>=4 else 0)

## 5.按消费日期月份、MOB分组计算逾期状态的情况
M1_V=df_stmp_all[["消费日期月份","MOB","M1+"]].groupby(["消费日期月份","MOB"]).agg({"sum","count"}).reset_index()
M1_V.columns=["消费日期月份","MOB","数量","坏数量"]
M1_V["M1+比例"]=M1_V["坏数量"]/M1_V["数量"]
M2_V=df_stmp_all[["消费日期月份","MOB","M2+"]].groupby(["消费日期月份","MOB"]).agg({"sum","count"}).reset_index()
M2_V.columns=["消费日期月份","MOB","数量","坏数量"]
M2_V["M2+比例"]=M2_V["坏数量"]/M2_V["数量"]
M3_V=df_stmp_all[["消费日期月份","MOB","M3+"]].groupby(["消费日期月份","MOB"]).agg({"sum","count"}).reset_index()
M3_V.columns=["消费日期月份","MOB","数量","坏数量"]
M3_V["M3+比例"]=M3_V["坏数量"]/M3_V["数量"]
M4_V=df_stmp_all[["消费日期月份","MOB","M4+"]].groupby(["消费日期月份","MOB"]).agg({"sum","count"}).reset_index()
M4_V.columns=["消费日期月份","MOB","数量","坏数量"]
M4_V["M4+比例"]=M4_V["坏数量"]/M4_V["数量"]


# pmml转换
# 0.导入包
import pandas as pd
import numpy as np
import os
#import scorecardpy as sc
from sklearn.model_selection import train_test_split
from sklearn import tree
from joblib import Parallel, delayed
import statsmodels.api as sm
from pylab import *
import joblib
#from Logistic_function_def import *

from sklearn_pandas import DataFrameMapper
from sklearn2pmml.pipeline import PMMLPipeline
from sklearn2pmml.preprocessing import ExpressionTransformer  


## 1.建模样本导入
df_model=pd.read_csv(r"C:\Users\user2\建模\2.建模\df_model.csv")

## 2.好坏样本分层抽样
bad_set = df_model[df_model['flagy'] == 1]
good_set = df_model[df_model['flagy'] == 0]
good_train,good_test = train_test_split(good_set,test_size = 0.3,random_state = 666)
bad_train,bad_test = train_test_split(bad_set,test_size = 0.3,random_state = 666)
train = pd.concat([good_train,bad_train])
test1 = pd.concat([good_test,bad_test])

## 3.变量转换
als_m12_id_nbank_orgnum_woe="-0.691944 if X[0]<2.5 else (-0.115891 if X[0]<6.5 else (0.44444 if X[0]<8.5 else (0.633443 if X[0]<11.5 else (0.830732 if X[0]<17.5 else (1.381016 if X[0]>=17.5 else -1.218068)))))"
edu_woe="-0.420906 if X[0]<2.5 else 0.060205"
rate3_02_woe="-1.856397 if X[0]<16.486 else (-0.778617 if X[0]<41.384 else (-0.3716 if X[0]<60.165 else (0.228992 if X[0]<93.609 else 0.673447)))"
mob_woe="0.338033 if X[0]<79.5 else (0.011561 if X[0]<589.5 else -0.099312)"
als_m3_id_nbank_nsloan_orgnum_woe="0.18661 if X[0]<1.5 else (1.202945 if X[0]>=1.5 else -0.342326)"
marr_woe="-0.116879 if X[0]=='YIUHUN' else 0.347435"
gen_woe="-0.327049 if X[0]=='F' else 0.181488"

trans = DataFrameMapper([
(['als_m12_id_nbank_orgnum'], ExpressionTransformer(als_m12_id_nbank_orgnum_woe)),
(['rate3_02'], ExpressionTransformer(rate3_02_woe)),
(['mob'], ExpressionTransformer(mob_woe)),
(['als_m3_id_nbank_nsloan_orgnum'], ExpressionTransformer(als_m3_id_nbank_nsloan_orgnum_woe)),
(['edu'], ExpressionTransformer(edu_woe)),
(['marr'], ExpressionTransformer(marr_woe)),
(['gen'], ExpressionTransformer(gen_woe)),
])

## 4.模型训练
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(penalty="none", solver="newton-cg", n_jobs=-1)

train_X=train[["als_m12_id_nbank_orgnum","rate3_02","mob","als_m3_id_nbank_nsloan_orgnum","edu","marr","gen"]]
train_Y=  train["flagy"]  

pipeline = PMMLPipeline([("trans",trans),("lr", lr)])
pipeline.fit(train_X,train_Y)
pipeline.predict_proba(train_X.head(1))[:, 1] # 检查

# from sklearn2pmml import sklearn2pmml
# sklearn2pmml(pipeline, r"C:\Users\user2\建模\2.建模\lr.pmml", with_repr = True)












